import React, { useEffect, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { 
  Table, 
  Card, 
  Tag, 
  Button, 
  message, 
  Space, 
  Tooltip,
  Typography
} from 'antd';
import { 
  MessageOutlined, 
  CalendarOutlined,
  RobotOutlined,
  UserOutlined,
  SyncOutlined,
  ClockCircleOutlined
} from '@ant-design/icons';
import { getChatSessionInfoBatch } from '@/services/ant-design-pro/chatController';
import { useModel } from '@umijs/max';

const { Title, Text } = Typography;

// 模型标签颜色映射
const modelTagColor: Record<string, string> = {
  'deepseek-r1': 'purple',
  'deepseek-v3': 'blue',
  'qwen-max': 'red',
  '默认模型': 'default'
};

// 状态标签颜色映射
const statusTagColor: Record<number, string> = {
  0: 'default', // 归档状态
  1: 'green'    // 活跃状态
};

const ChatSessionInfoPage: React.FC = () => {
  const [loading, setLoading] = useState<boolean>(false);
  const [sessions, setSessions] = useState<API.ChatSessionInfoDTO[]>([]);
  const [agentType, setAgentType] = useState<string>('CHAT');
  const { initialState } = useModel('@@initialState');
  const currentUser = initialState?.currentUser;

  // 获取聊天会话信息列表
  const fetchChatSessionInfo = async () => {
    setLoading(true);
    try {
      const res = await getChatSessionInfoBatch({ agentType });
      
      // 检查API响应
      if (res && res.code === 0 && res.data) {
        setSessions(res.data);
        
        // 如果数据为空数组，显示信息提示
        if (res.data.length === 0) {
          message.info('暂无聊天会话信息');
        }
      } else {
        // 显示错误信息
        const errorMsg = res?.message || '获取聊天会话信息失败';
        message.error(errorMsg);
        console.error('API返回错误:', res);
      }
    } catch (error) {
      console.error('获取聊天会话信息失败:', error);
      message.error('获取聊天会话信息失败，请检查网络连接');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchChatSessionInfo();
  }, [agentType]);

  // 格式化日期显示
  const formatDate = (dateString?: string) => {
    if (!dateString) return '-';
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  // 定义表格列
  const columns = [
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      render: (text: string, record: API.ChatSessionInfoDTO) => (
        <Space>
          <MessageOutlined style={{ color: '#4f46e5' }} />
          <Text strong>{text || '未命名对话'}</Text>
        </Space>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: (text: string) => (
        <Space>
          <CalendarOutlined />
          {formatDate(text)}
        </Space>
      ),
    },
    {
      title: '最后消息时间',
      dataIndex: 'lastMessageTime',
      key: 'lastMessageTime',
      render: (text: string) => (
        <Space>
          <ClockCircleOutlined />
          {formatDate(text)}
        </Space>
      ),
    },
    {
      title: '消息数量',
      dataIndex: 'messageCount',
      key: 'messageCount',
      render: (count: number) => (
        <Tag color="blue">{count} 条消息</Tag>
      ),
    },
    {
      title: '模型类型',
      dataIndex: 'modelType',
      key: 'modelType',
      render: (text: string) => (
        <Tag color={modelTagColor[text] || 'default'} icon={<RobotOutlined />}>
          {text || '未知模型'}
        </Tag>
      ),
    },
    {
      title: '代理类型',
      dataIndex: 'agentType',
      key: 'agentType',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: number) => (
        <Tag color={statusTagColor[status] || 'default'}>
          {status === 1 ? '活跃' : '归档'}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: API.ChatSessionInfoDTO) => (
        <Space size="middle">
          <Button 
            type="link" 
            onClick={() => window.location.href = `/chat?chatId=${record.chatId}`}
          >
            查看对话
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer
      header={{
        title: '聊天会话信息',
        ghost: true,
      }}
    >
      <Card>
        <div style={{ marginBottom: 16 }}>
          <Space>
            <Button 
              type="primary"
              icon={<SyncOutlined />}
              onClick={fetchChatSessionInfo}
              loading={loading}
            >
              刷新
            </Button>
            <Button
              onClick={() => window.location.href = '/chat'}
            >
              返回聊天
            </Button>
          </Space>
        </div>
        <Table 
          columns={columns} 
          dataSource={sessions} 
          rowKey="chatId"
          loading={loading}
          pagination={{ 
            showSizeChanger: true, 
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条聊天会话`,
          }}
        />
      </Card>
    </PageContainer>
  );
};

export default ChatSessionInfoPage; 